const redis = require('redis');
// // const client = redis.createClient({ url: 'redis://localhost:6379' }); // 替换为你的Redis URL
// const config = {
//   url: 'http://192.168.1.6:3004',
//   port: 6379,
//   password: '设置的Redis密码'
// }
// const client = redis.createClient(config.port, config.url); // 实例redis对象
//// 连接错误处理
// client.on('error',(err) => {
//   console.log('reds client error',err)
// })


// import { createClient } from 'redis';
// const client = redis.createClient({host:'127.0.0.1',port:6379});
// const client = redis.createClient({url:'redis://127.0.0.1:6379',port:6379});
const client = redis.createClient({url:'redis://192.168.1.6:6379',port:6379});

client.on('error', err => console.log('Redis Client Error', err));

client.connect(()=>{
  console.log('redis 连接成功');
});


client.on('connect', () => {
  console.log('redis connect success');
})
module.exports = {
  // 存储短信验证码
storeSmsCode: function(phoneNumber, code) {
  console.log('redis:' + JSON.stringify(redis))
  console.log('client:' + JSON.stringify(client))
  console.log('storeSmsCode is doing')
  console.log(`phoneNumber:${phoneNumber} code:${code}`)
  client.set(`sms_code:${phoneNumber}`, code);
  client.expire(`sms_code:${phoneNumber}`, 5 * 60); // 设置验证码过期时间为5分钟
  
},
// 验证短信验证码
validateSmsCode: function(phoneNumber, code) {
  client.get(`sms_code:${phoneNumber}`, (err, storedCode) => {
    if (err) throw err;
    if (storedCode === code) {
      console.log('验证码正确');
      // 验证码正确后，可以选择删除这个验证码或者让它过期
      client.del(`sms_code:${phoneNumber}`);
    } else {
      console.log('验证码错误');
    }
  });
}
// // 存储短信验证码
// function storeSmsCode(phoneNumber, code) {
//   console.log('storeSmsCode is doing')
//   console.log(`phoneNumber:${phoneNumber} code:${code}`)
//   client.set(`sms_code:${phoneNumber}`, code);
//   client.expire(`sms_code:${phoneNumber}`, 5 * 60); // 设置验证码过期时间为5分钟
// }
 
// // 验证短信验证码
// function validateSmsCode(phoneNumber, code) {
//   client.get(`sms_code:${phoneNumber}`, (err, storedCode) => {
//     if (err) throw err;
//     if (storedCode === code) {
//       console.log('验证码正确');
//       // 验证码正确后，可以选择删除这个验证码或者让它过期
//       client.del(`sms_code:${phoneNumber}`);
//     } else {
//       console.log('验证码错误');
//     }
//   });
// }
}
 
// // 示例：存储验证码
// storeSmsCode('13812345678', '123456');
 
// // 示例：验证验证码
// validateSmsCode('13812345678', '123456');
